const fs = require('fs');
const path = require('path');

/**
 * @description: 获取当前文件的版本号
 * @return {*}
 */
const getCurrentVersion = () => {
  const packageJson = fs.readFileSync(path.join(__dirname, './version.json'), 'utf8');
  const packageJsonObj = JSON.parse(packageJson);
  return packageJsonObj.version;
};

/**
 * @description: 增加指定版本级别
 * @param {*} version
 * @param {*} type
 * @return {*}
 */
function increaseVersion(version, type) {
  let parts = version.split('.');
  switch (type) {
    case 'patch':
      parts[2] = String(Number(parts[2]) + 1);
      break;
    case 'minor':
      parts[1] = String(Number(parts[1]) + 1);
      parts[2] = '0';
      break;
    case 'major':
      parts[0] = String(Number(parts[0]) + 1);
      parts[1] = '0';
      parts[2] = '0';
      break;
    default:
      console.log('Invalid version type');
      return version;
  }
  return parts.join('.');
}

/**
 * @description: 更新版本号
 * @param {string} updateLevel "major" | "minor" | "patch"
 * @return {*}
 */
const updateCurrentVersion = (updateLevel = 'patch') => {
  let version = getCurrentVersion();
  console.log('当前版本号: ', version);
  let nextVersion = increaseVersion(version, updateLevel);
  console.log('升级之后的版本号: ', nextVersion);
  fs.writeFileSync(path.join(__dirname, '../public/version.json'), JSON.stringify({ version: nextVersion }));
};

/**
 * @description: 直接用参数修改版本号
 * @param {*} version
 * @return {*}
 */
const updateVersionByParams = (version) => {
  console.log('版本号: ', version);
  fs.writeFileSync(path.join(__dirname, '../public/version.json'), JSON.stringify({ version: version }));
};

module.exports = {
  getCurrentVersion,
  updateCurrentVersion,
  updateVersionByParams
};
